# -*- coding: utf-8 -*-
# @Time : 2022/6/19 10:50
# @Author : cheney
# @File : simulate_base_station.py
# @Software: PyCharm
# @Site: www.cheney.cc


import socket
from pi.config import *
import threading
import json
from pynput.keyboard import Listener
import time

# 监测按键：https://blog.csdn.net/qq_44741568/article/details/97895880

"""
这里模拟一下基站，发送指令，接收数据

ADSW四个按键充当方向键进行操作
"""
_dir = [False, False, False, False]  # 前后左右四个按钮
new_sock = socket.socket


def on_press(key):
    global _dir
    _dir_old = _dir.copy()
    if "'w'" == str(key):
        print("\r按下--前进", end="")
        _dir[0] = True

    if "'s'" == str(key):
        print("\r按下--后退", end="")
        _dir[1] = True

    if "'a'" == str(key):
        print("\r按下--左转", end="")
        _dir[2] = True

    if "'d'" == str(key):
        print("\r按下--右转", end="")
        _dir[3] = True

    if _dir != _dir_old:
        my_send(_dir)


def on_release(key):
    global _dir
    _dir_old = _dir.copy()

    if "'w'" == str(key):
        print("松开--前进")
        _dir[0] = False

    if "'s'" == str(key):
        print("松开--后退")
        _dir[1] = False

    if "'a'" == str(key):
        print("松开--左转")
        _dir[2] = False

    if "'d'" == str(key):
        print("松开--右转")
        _dir[3] = False

    if _dir != _dir_old:
        my_send(_dir)


def my_send(dir_list):
    print("send", dir_list)
    packet = {
        "src_id": "192.168.34.53",
        "dst_id": "192.168.34.53",

        "pac_type": 2,
        "ctl_type": 0,

        "timestamp": "2022-05-13 18:22:35",

        "content": {
            "direction": [False, False, False, False],
            "speed": 70,
            "diff_speed": 20,
        }
    }
    packet["content"]["direction"] = dir_list
    global new_sock
    new_sock.send((json.dumps(packet)).encode('utf-8'))


def service_thread_send(_sock: socket.socket):
    """
    收到新的连接，先判断该连接的类型，然后交给对应的函数处理
    :param _sock: 收发报文对应的socket
    :return:
    """

    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()


def service_thread_recv(_sock: socket.socket):
    while True:
        data_bin = _sock.recv(1024)
        if data_bin == b"":  # 断开
            print("断开连接")
            _sock.close()
            return
        print("收到数据:", json.loads(data_bin.decode("utf-8")))


if __name__ == '__main__':
    s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建套接字
    s_sock.bind((addr_BaseStation_1, port_BaseStation_1))
    s_sock.listen(5)  # socket的”排队个数“为5 ！！！不是最大连接数

    while True:
        print("listening: ", s_sock)
        new_sock, adress = s_sock.accept()  # 这条命令是阻塞的
        print("连接成功")
        threading.Thread(target=service_thread_recv, args=(new_sock,)).start()  # 收到新的请求就直接投入新的线程并且开始运行
        threading.Thread(target=service_thread_send, args=(new_sock,)).start()  # 收到新的请求就直接投入新的线程并且开始运行

"""
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/iot-trolley-system/pi/main/main.py", line 87, in send_back_data
    ret = _sock.send(_mypac.to_bin())  # 对象转二进制再发送出去
    
  File "/opt/iot-trolley-system/pi/model/packet.py", line 95, in to_bin
    return self.__to_json().encode(encoding=encoding)
  File "/opt/iot-trolley-system/pi/model/packet.py", line 134, in __to_json
    "content": self.content.to_json()
    
  File "/opt/iot-trolley-system/pi/model/data.py", line 67, in to_json
    return str(json.dumps(_ans))
  File "/usr/lib/python3.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type instruction is not JSON serializable
"""